const { Routers } = require('../../model');

// 路由模型
/**
 * @param {string} path 路由路径
 * @param {string} icon 路由图标
 * @param {string} status 路由状态
 * @param {string} menuName 路由标题
 * @param {string} orderNum 路由组件
 * @param {string} menuType 菜单类型
 * @param {string} parentId 父节点id
 * @param {*} req
 * @param {*} res
 */

// 添加路由
const addRouter = async (req, res) => {
  console.log('添加路由');
  const { path = '', icon = '', status, menuName, orderNum = 0, menuType, parentId } = req.body;
  try {
    const [router, created] = await Routers.findOrCreate({
      where: {
        path,
      },
      defaults: {
        path,
        icon,
        status,
        menuName,
        orderNum,
        menuType,
        parentId,
      },
    });
    if (created) {
      res.json({
        errcode: 0,
        msg: '成功',
        data: router,
        success: true,
      });
    } else {
      res.send({
        errcode: 1,
        msg: '路径已添加',
        success: false,
      });
    }
  } catch (error) {
    res.send({
      errcode: 1,
      msg: '失败' + error,
      success: false,
    });
  }
};

// 编辑路由
const editRouter = async (req, res) => {
  const { id, path = '', icon = '', status, menuName, orderNum = 0, menuType, parentId } = req.body;
  console.log('编辑路由', id, path, icon, status, menuName, orderNum, menuType, parentId);
  try {
    const router = await Routers.update(
      { path, icon, status, menuName, orderNum, menuType, parentId },
      {
        where: {
          id,
        },
      }
    );
    if (router) {
      res.json({
        errcode: 0,
        msg: '成功',
        success: true,
      });
    } else {
      res.json({
        errcode: 1,
        msg: '失败',
        success: false,
      });
    }
  } catch (error) {
    res.send({
      errcode: 1,
      msg: '失败' + error,
      success: false,
    });
  }
};

// 删除路由
const deleteRouter = async (req, res) => {
  console.log('删除路由');
  const { id } = req.body;
  try {
    const router = await Routers.destroy({
      where: {
        id,
      },
    });
    if (router) {
      res.json({
        errcode: 0,
        msg: '成功',
        success: true,
      });
    } else {
      res.json({
        errcode: 1,
        msg: '失败',
        success: false,
      });
    }
  } catch (error) {
    res.send({
      errcode: 1,
      msg: '失败' + error,
      success: false,
    });
  }
};

// 路由列表
const routerList = async (req, res) => {
  console.log('路由列表');
  try {
    const routers = await Routers.findAndCountAll();
    if (!routers) {
      res.json({
        errcode: 1,
        msg: '失败',
        success: false,
        data: [],
      });
      return;
    }
    res.json({
      errcode: 0,
      msg: '成功',
      data: routers,
      success: true,
    });
  } catch (error) {
    res.send({
      errcode: 1,
      msg: '失败' + error,
      success: false,
    });
  }
};

module.exports = {
  addRouter,
  editRouter,
  deleteRouter,
  routerList,
};
